package com.leyou.user.web;

import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.exception.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.enity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

@SuppressWarnings("ALL")
/**
 * @Description :
 * @author     :LD
 */
@RestController
@RequestMapping("info")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("exists/{data}/{type}")
    public ResponseEntity<Boolean> isExists(@PathVariable("data")String data,@PathVariable("type")Integer type){
        Boolean f = userService.isExists(data,type);
        return ResponseEntity.ok(f);
    }

    @PostMapping("code")
    public ResponseEntity<Void> sendMessage(@RequestParam("phone")String phone){
        userService.sendMessage(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    @PostMapping
    public ResponseEntity<Void> register(@Valid User user, BindingResult result, @RequestParam("code")String code){
        if (result.hasErrors()){
            String msg = result.getFieldErrors().stream().map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            throw new LyException(400, msg);
        }
        userService.register(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @GetMapping
    public ResponseEntity<UserDTO> queryUserByPhoneAndPassword(@RequestParam("username")String username,@RequestParam("password")String password){
        return ResponseEntity.ok(userService.queryUserByPhoneAndPassword(username,password));
    }

    @GetMapping("me")
    public ResponseEntity<UserDetail> me(){
        return ResponseEntity.ok(UserContext.getUser());
    }
}
